import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";
import "../theme/index.css";
import ElementUI from "element-ui";

Vue.use(ElementUI);
let http = axios.create({
  baseURL: "https://api.masterhorizons.com/"
});

// 添加请求拦截器
http.interceptors.request.use(
  function(config) {
    // 在发送请求之前做些什么
    if (localStorage.getItem("user_token")) {
      // 判断是否存在token，如果存在的话，则每个http header都加上token
      config.headers["X-Api-Token"] = localStorage.getItem("user_token");
    }
    return config;
  },
  function(error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
http.interceptors.response.use(
  function(res) {
    // 对响应数据做点什么
    if (res.data.code !== 0) {
      Vue.prototype.$notify({
        title: "错误",
        message: res.data.message,
        type: "error"
      });
      if (res.data.code == 10 || res.data.code == 11 || res.data.code == 12) {
        localStorage.clear();
        location.reload();
      }
    } else {
      return res.data.data;
    }
  },
  function(error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

Vue.prototype.$axios = http;
Vue.use(Vuex);
export default new Vuex.Store({
  state: {
    company_name: "",
    company_logo: "",
    company_copyright: "",
    url: "https://api.masterhorizons.com/",
    is_vip: false,
    is_login: localStorage.getItem("user_token") ? true : false,
    show_recharge: false,
    show_login: false,
    show_set: false,
    show_search: false,
    group_id: "",
    group_price: "",
    order_type: "vip",
    mine_index: 0
  },
  mutations: {
    logout() {
      localStorage.clear();
      location.href = "http://" + location.host;
    }
  }
});
